<?php
/**
 * Created by PhpStorm.
 * User: JYuans
 * Date: 2019/12/11
 * Time: 15:54
 */
namespace Bstage\Controller;

class TeamExamineRelationDownController extends BstageController {

    /**
     * 查询班子考评，员工考评设置列表
     */
    public function relationDownList(){
        $team_examine_id = $_REQUEST['team_examine_id'] ? $_REQUEST['team_examine_id'] : $this->errorReturn("缺少班子考评ID");

        $team_list = M("TeamExamineRelationDown")
            ->alias("terd")
            ->where(['team_examine_id'=>$team_examine_id])
            ->group("be_examine_team_id")
            ->join("__TEAM__ t on terd.be_examine_team_id = t.team_id")
            ->field("t.team_id,t.name,count(examine_user_id) as user_count,sum(comprehensive_status) as complete_count")
            ->select();
        if(!$team_list){
            $this->returnJson(503,"无数据");
        }

        $this->successReturn("获取成功",$team_list);
    }

    /**
     * 查看班子临时账号列表
     */
    public function getTeamTemporaryUserList(){
        $team_examine_id = $_REQUEST['team_examine_id'] ? $_REQUEST['team_examine_id'] : $this->errorReturn("缺少班子考评ID");
        $team_id = $_REQUEST['team_id'] ? $_REQUEST['team_id'] : $this->errorReturn("缺少班子ID");

        $user_list = M("User")
            ->alias("u")
            ->join("__TEAM_EXAMINE_RELATION_DOWN__ trd on u.user_id = trd.examine_user_id")
            ->where(['team_examine_id'=>$team_examine_id,'trd.be_examine_team_id'=>$team_id])
            ->field("u.user_id,u.username,u.t_user_pass")
            ->select();
        if(!$user_list){
            $this->returnJson(503,"无数据");
        }
        foreach($user_list as $key=>$value){
            $user_list[$key]['password'] = $value['t_user_pass'];
        }
        $this->successReturn("获取成功",['list_data'=>$user_list]);
    }


    /**
     * 添加临时账号接口
     */
    public function addTemporaryUser(){
        $user_count = is_numeric($_REQUEST["user_count"])?$_REQUEST["user_count"]:$this->errorReturn("请输入需要生成的账号数量，参数必须为数字");

        $team_examine_id = $_REQUEST['team_examine_id'] ? $_REQUEST['team_examine_id'] : $this->errorReturn("缺少班子考评ID");

        $team_examine_data = M("TeamExamine")
            ->where(['team_examine_id'=>$team_examine_id])
            ->field("status")
            ->find();
        if(!$team_examine_data){
            $this->errorReturn("考评ID错误");
        }
        /*if($team_examine_data['status'] >=2){
            $this->errorReturn("考评已开始或已结束，无法添加");
        }*/

        $team_id = $_REQUEST["team_id"]?$_REQUEST["team_id"]:$this->errorReturn("请选择考评班子");

        $check_team_id = M("Team")
            ->where(['team_id'=>$team_id])
            ->count();
        if(!$check_team_id){
            $this->errorReturn("班子ID错误");
        }

        if($user_count <= 0){
            $this->errorReturn("生成账号数量必须大于0");
        }

        $use_start_time = $_REQUEST["use_start_time"]?strtotime($_REQUEST["use_start_time"]):$this->errorReturn("请输入临时账号使用期限，开始时间");
        $use_end_time = $_REQUEST["use_end_time"]?strtotime($_REQUEST["use_end_time"])+86399:$this->errorReturn("请输入临时账号使用期限，结束时间");

        if($use_start_time >= $use_end_time){
            $this->errorReturn("期限结束时间必须大于当前时间");
        }

        $new_data = array();
        $new_data['depart_id'] = 0;
        $new_data['rank'] = 1;
        $new_data['user_type'] = 0;
        $new_data['add_time'] = time();
        $new_data['use_start_time'] = $use_start_time;
        $new_data['use_end_time'] = $use_end_time;

        //获取临时账号前缀标识
        /*$username_flag = $this->generateTemporaryUsername();
        if(!$username_flag){
            $this->errorReturn("获取临时账号标识失败，请重新尝试");
        }
        $username_flag = "T".$username_flag;

        //获取临时账号后续字符串
        $str_len = strlen($user_count);
        $str_flag = "";
        for($i = 0;$i < $str_len;$i++){
            $str_flag = $str_flag."0";
        }*/

        $model = M();
        $model->startTrans();

        //循环生成账号数据
        for($i = 0;$i < $user_count;$i++){
            $current_i = $i + 1;
            /*$new_data['username'] = $username_flag.mb_substr($str_flag,0,$str_len - strlen($current_i)).$current_i;
            $new_data['password'] = md5($new_data['username']);*/
            do{
                $new_data['username'] = randnumkeys(8);
                $check_username = M("User")
                    ->where(['username'=>$new_data['username']])
                    ->count();
            }while($check_username);
            $new_data['t_user_pass'] = randnumkeys(8);
            $new_data['password'] = md5($new_data['t_user_pass']);
            $new_data['name'] = $new_data['username'];

            $add_user_result = M("User")
                ->add($new_data);
            if(!$add_user_result){
                $model->rollback();
                $this->errorReturn("添加账号失败，请重新尝试");
            }

            //team_examine_id,be_examine_team_id,examine_user_id
            $new_down_relation = array();
            $new_down_relation['team_examine_id'] = $team_examine_id;
            $new_down_relation['be_examine_team_id'] = $team_id;
            $new_down_relation['examine_user_id'] = $add_user_result;

            $add_down_relation_result = M("TeamExamineRelationDown")
                ->add($new_down_relation);
            if(!$add_down_relation_result){
                $model->rollback();
                $this->errorReturn("添加账号关系失败，请重新尝试");
            }
        }

        $model->commit();
        $this->successReturn("临时账号生成成功");
    }

    /**
     * 删除班子考评员工账号接口
     */
    public function deleteTemporaryUser(){
        $team_examine_id = $_REQUEST['team_examine_id'] ? $_REQUEST['team_examine_id'] : $this->errorReturn("缺少班子考评ID");
        $team_id_json = $_REQUEST["team_id_json"]?$_REQUEST["team_id_json"]:$this->errorReturn("请选择考评班子");

        $team_id_array = json_decode($team_id_json,true);
        if(!$team_id_array || !is_array($team_id_array)){
            $this->errorReturn("请选择考评班子");
        }

        $team_user_id_array = M("TeamExamineRelationDown")
            ->where(['team_examine_id'=>$team_examine_id,'be_examine_team_id'=>['in',$team_id_array]])
            ->getField("examine_user_id",true);
        if(!$team_user_id_array){
            $this->errorReturn("班子考评ID或班子ID错误，请重新尝试");
        }

        $model = M();
        $model->startTrans();

        $delete_user_result = M("User")
            ->where(['user_id'=>['in',$team_user_id_array]])
            ->delete();
        if(!$delete_user_result){
            $model->rollback();
            $this->errorReturn("删除临时账号失败，请重新尝试");
        }

        $delete_relation_result = M("TeamExamineRelationDown")
            ->where(['team_examine_id'=>$team_examine_id,'be_examine_team_id'=>['in',$team_id_array]])
            ->delete();
        if(!$delete_relation_result){
            $model->rollback();
            $this->errorReturn("删除临时账号关系数据失败，请重新尝试");
        }

        $model->commit();
        $this->successReturn("删除成功");
    }

    /**
     * 查询班子考评，员工考评情况列表
     */
    public function downExamineInfoList(){
        $team_examine_id = $_REQUEST['team_examine_id'] ? $_REQUEST['team_examine_id'] : $this->errorReturn("缺少班子考评ID");

        $team_list = M("TeamExamineRelationDown")
            ->alias("terd")
            ->where(['team_examine_id'=>$team_examine_id])
            ->group("be_examine_team_id")
            ->join("__TEAM__ t on terd.be_examine_team_id = t.team_id")
            ->field("t.team_id,t.name,count(examine_user_id) as examine_count,sum(comprehensive_status) as examine_complete_count")
            ->select();
        if(!$team_list){
            $this->returnJson(503,"无数据");
        }

        $this->successReturn("获取成功",$team_list);
    }

    /**
     * 查询班子考评，员工考评详情
     */
    public function downExamineInfo(){
        $team_examine_id = $_REQUEST['new_team_examine_id'] ? $_REQUEST['new_team_examine_id'] : $this->errorReturn("缺少班子考评ID");

        $team_examine_data = M("TeamExamine")
            ->where(['team_examine_id'=>$team_examine_id])
            ->field("item_json")
            ->find();
        if(!$team_examine_data){
            $this->errorReturn("班子考评ID错误，请重新尝试");
        }

        $team_id = $_REQUEST['team_id'] ? $_REQUEST['team_id'] : $this->errorReturn("缺少班子ID");

        $team_name = M("Team")
            ->where(['team_id'=>$team_id])
            ->getField("name");
        if(!$team_name){
            $this->errorReturn("班子ID错误");
        }

        $team_examine_list = M("TeamExamineRelationDown")
            ->where(['team_examine_id'=>$team_examine_id,'be_examine_team_id'=>$team_id,'comprehensive_status'=>1])
            ->field("item_result,item_score")
            ->select();
        $amount_item_result = array();
        $amount_score = 0;
        foreach($team_examine_list as $key=>$value){
            $team_examine_list[$key]['item_result'] = json_decode($value['item_result'],true);
            if(!$amount_item_result){
                $amount_item_result = $team_examine_list[$key]['item_result'];
            }else{
                for($i=0;$i<count($amount_item_result);$i++){
                    $amount_item_result[$i] = bcadd($amount_item_result[$i],$team_examine_list[$key]['item_result'][$i],2);
                }
            }
            $amount_score = bcadd($amount_score,$value['item_score'],2);
        }

        $all_submit_count = count($team_examine_list);
        for($i=0;$i<count($amount_item_result);$i++){
            $amount_item_result[$i] = bcdiv($amount_item_result[$i],$all_submit_count,2);
        }
        $amount_score = bcdiv($amount_score,$all_submit_count,2);

        $return_data = array();
        $return_data['team_name'] = $team_name;
        $return_data['item_array'] = json_decode($team_examine_data['item_json']);
        $return_data['team_examine_list'] = $team_examine_list;
        $return_data['avg_item_result'] = $amount_item_result;
        $return_data['avg_score'] = $amount_score;

        $this->successReturn("获取成功",$return_data);
    }
}